<?php

namespace App\Services\AliyunOSS;

require_once base_path().'/vendor/aliyuncs/oss-sdk-php/autoload.php';

use OSS\OssClient;
use OSS\Core\OssException;
use Config;
use Log;

/**
* 阿里云OSS服务
*/
class OSS
{
	
	private $ossClient;

	public function __construct()
	{
		$accessKeyId     = Config::get('app.oss.accessKeyId');
		$accessKeySecret = Config::get('app.oss.accessKeySecret');
		$endpoint        = Config::get('app.oss.endpoint');
		$this->ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
	}

	/**
	 * 上传文件
	 * @param $key 文件名
	 * @param $filePath 文件路径
	 * @param $bucket 桶名
	 * @return json
	 */
	public static function upload($key, $filePath, $bucket = 'imlooke')
	{
		$oss = new OSS();
		
		try {
			$oss->ossClient->putObject($bucket, $key, $filePath);
			return 'upload succeed!';
		} catch (OssException $e) {
			Log::error('aliyun oss error: '.$e->getMessage());
		}
	}

	/**
	 * 删除文件
	 * @param $key 文件名
	 * @param $bucket 桶名
	 */
	public static function deleteObject($key, $bucket = 'imlooke')
	{
		$oss = new OSS();

		try{
	        $oss->ossClient->deleteObject($bucket, $key);
	        return 'delete succeed!';
	    } catch(OssException $e) {
	        Log::error('aliyun oss error: '.$e->getMessage());
	    }
	}
}